package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.beans.beancontext.BeanContext;
import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        // 拷贝员工（拷贝到 emp）
        BeanUtils.copyProperties(employeeDTO, emp);
        // 补充员工信息
        emp.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));  // 加密密码
        emp.setStatus(StatusConstant.ENABLE);  // 设置员工状态
//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
        // 设置新增员工和修改员工的操作员 ID
//        emp.setCreateUser(BaseContext.getCurrentId());
//        emp.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.addEmployee(emp);
    }

    /**
     * 员工分页查询
     */
    @Override
    public PageResult findPagination(EmployeePageQueryDTO employeePageQueryDTO) {
        // 调用 pageHelper
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.findPagination(employeePageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 启用、禁用员工账号
     * @param status
     */
    @Override
    public void setStatus(Integer status, Long id) {
        // 构造实体对象
        Employee emp = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.updateEmp(emp);
    }

    /**
     * 根据 ID 查询员工
     * @param id
     * @return
     */
    @Override
    public Employee findById(Integer id) {
        Employee emp = employeeMapper.findById(id);
        emp.setPassword("******");
        return emp;
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        // 拷贝员工信息
        BeanUtils.copyProperties(employeeDTO, emp);
        // 补全员工信息
//        emp.setUpdateTime(LocalDateTime.now());
//        emp.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(emp);
    }
}
